package com.wudizaba.microservicesdemosystem.config;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.wudizaba.microservicesdemocommon.constant.QuartzConstant;
import com.wudizaba.microservicesdemosystem.config.MqttJob.DetectDeviceJob;
import com.wudizaba.microservicesdemosystem.module.po.QuzrtzJobs;
import com.wudizaba.microservicesdemosystem.service.IQuzrtzJobsService;
import com.wudizaba.microservicesdemosystem.util.QuartzUtils;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;

import java.util.Date;

/**
 * 定时任务
 *
 * @author wudizaba
 */
@Configuration
public class SchedulerConfiguration implements ApplicationRunner {

    @Autowired
    private IQuzrtzJobsService quzrtzJobsService;

    @Autowired
    private Scheduler scheduler;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 定时检测设备是否在线
        Date date = QuartzUtils.createJobAndTrigger(DetectDeviceJob.class, QuartzConstant.DETECT_DEVICE_JOB_NAME
                , QuartzConstant.DETECT_DEVICE_JOB_GROUP, QuartzConstant.TRIGGER_NAME
                , QuartzConstant.TRIGGER_GROUP, QuartzConstant.DETECT_DEVICE_JOB_CRON, scheduler);
        QuzrtzJobs quzrtzJobs = new QuzrtzJobs();
        quzrtzJobs.setJobName(QuartzConstant.DETECT_DEVICE_JOB_NAME);
        quzrtzJobs.setJobGroup(QuartzConstant.DETECT_DEVICE_JOB_GROUP);
        quzrtzJobs.setTriggerId(QuartzConstant.TRIGGER_NAME);
        quzrtzJobs.setTriggerGroup(QuartzConstant.TRIGGER_GROUP);
        quzrtzJobs.setSchedule(QuartzConstant.DETECT_DEVICE_JOB_CRON);
        quzrtzJobs.setStatus(1);
        quzrtzJobs.setLastRun(LocalDateTimeUtil.of(date));

        quzrtzJobsService.save(quzrtzJobs);
    }
}
